﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using UpLoadPSDataSystem.Properties;
using UpLoadPSDataSystem.Util;
using MessageBox = System.Windows.MessageBox;

namespace UpLoadPSDataSystem
{
    public partial class FormMain : Form
    {
        SqlConnection _skpwConnection;
        // = new SqlConnection("server=.;database=DB_TotalControl_SX_New;uid=sa;pwd=hello;");

        SqlCommand _skpwCommand;

        SqlConnection _xpsConnection;
        // = new SqlConnection("server=.;database=DB_TotalControl_SX_New;uid=sa;pwd=hello;");

        SqlCommand _xpsCommand;
        SqlDataAdapter _sda;
        SqlDataAdapter _xpsSda;

        public FormMain()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            try
            {
                _skpwConnection = new SqlConnection(Settings.Default.SKPW_ConnectionString);
                _skpwCommand = new SqlCommand
                {
                    Connection = _skpwConnection,
                    CommandType = CommandType.Text
                };
                _xpsConnection = new SqlConnection(Settings.Default.SXXPS_ConnectionString);
                _xpsCommand = new SqlCommand
                {
                    Connection = _xpsConnection,
                    CommandType = CommandType.Text
                };
            }
            catch (Exception ex)
            {
                LogHelper.Error(typeof(FormMain), ex);
                rtbError.Text = ex.Message + ex.StackTrace;
            }
            (new Thread(timer1_Tick)).Start();
            // (new Thread(timer2_Tick)).Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void timer1_Tick()
        {
            int times = 0;
            while (true)
            {
                try
                {
                    //Reissue();
                    LoadXpsData();

                    tbTimes.Text = (++times).ToString();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(typeof(FormMain), ex);
                    rtbError.Text = ex.Message + ex.StackTrace;
                }
                finally
                {
                    ThreadSleep(Settings.Default.Interval);
                }
            }
        }

        //private void timer2_Tick()
        //{

        //    while (true)
        //    {
        //        try
        //        {
        //            Reissue();
        //        }
        //        catch (Exception ex)
        //        {
        //            LogHelper.Error(typeof(FormMain), ex);
        //            rtbError.Text = ex.Message + ex.StackTrace;
        //        }
        //        finally
        //        {
        //            ThreadSleep(1 * 60 * 60 * 1000);
        //        }
        //    }
        //}

        //private void Reissue()
        //{
        //    try
        //    {
        //        List<int> ports = Helper.Ports();
        //        var mappings = Helper.Mappings();
        //        int count1 = 0;
        //        foreach (var portitem in ports)
        //        {
        //            count1++;
        //            if (!mappings.ContainsKey(portitem)) continue;
        //            var port = portitem.ToString();
        //            try
        //            {
        //                using (var context = new OldToNewEntities())
        //                {
        //                    var now = DateTime.Now.AddHours(-2);
        //                    DateTime begin = now.AddDays(-Settings.Default.小时补传_天);
        //                    IQueryable<Envi_PS_Waste_Water_Flow_Hour_Correct_Data> hours = context
        //                        .Envi_PS_Waste_Water_Flow_Hour_Correct_Data.Where(t => t.Date_Time >= begin)
        //                        .Where(t => t.Date_Time <= now).Where(t => t.Let_Port_ID.Equals(port))
        //                        .OrderBy(t => t.ID);
        //                    var exsitHours = hours.Select(t => t.Date_Time).ToList();
        //                    var lostHours = DataLostAlgorithm.CheckData(exsitHours, begin, now, DataTypeEnum.Hour);
        //                    rtbInfo.Text = count1+"/"+ports.Count+mappings[portitem]+ "丢失数据("+begin+"--"+now+"):" + lostHours.Count;
        //                    int count2 = 0;
        //                    foreach (var lostHour in lostHours)
        //                    {
        //                        count2++;
        //                        var d = lostHour.ToString("yyyy-M-d");
        //                        var h = lostHour.ToString("H:");

        //                        var s = mappings[portitem];
        //                        var sqlString = $"select  * from {s} WITH(NOLOCK) where 日期='" + d +
        //                                        "' and  时间 like '" + h + "%'  order by 时间标志";
        //                        _xpsCommand.CommandText = sqlString;
        //                        if (_xpsConnection.State == ConnectionState.Closed)
        //                            _xpsConnection.Open();
        //                        if (_skpwConnection.State == ConnectionState.Closed)
        //                            _skpwConnection.Open();
        //                        DataTable dt = new DataTable();
        //                        _sda = new SqlDataAdapter(_xpsCommand);
        //                        _sda.Fill(dt);
        //                        //rtbInfo.Text = "丢失数据:" + dt.Rows.Count;
        //                        foreach (DataRow rowT in dt.Rows)
        //                        {
        //                            try
        //                            {
        //                                var id = rowT["时间标志"].ToString();
        //                                //string sql =
        //                                //    string.Format(
        //                                //        "UPDATE Envi_UploadXPSDataMapping SET LastMaxID={0} WHERE Let_Port_ID={1}",
        //                                //        id, portitem);
        //                                //_skpwCommand.CommandText = sql;
        //                                //_skpwCommand.ExecuteNonQuery();
        //                                // if (letPortId != "")
        //                                {
        //                                    var monitorTime = Convert.ToDateTime(rowT["日期"]).ToString("yyyy-MM-dd") +
        //                                                      " " + rowT["时间"];
        //                                    //var dateTime = DateTime.Parse(monitorTime);
        //                                    //if (dateTime > DateTime.Now.AddDays(-1) &&
        //                                    //    dateTime < DateTime.Now.AddDays(1))
        //                                    // && dateTime.Minute < 16)//2013-01-21 严添加时间判断（如果检测时间延时不超过一天）
        //                                    {
        //                                        var flow = Convert.ToDecimal(rowT["瞬时流量"]);
        //                                        var totalFlow = Convert.ToDecimal(rowT["累积流量"]);
        //                                        string sqlStr =
        //                                            $"exec SP_UploadSXXPS_Monitor_Data '{portitem}','{monitorTime}','{flow.ToString(CultureInfo.InvariantCulture)}','{totalFlow.ToString(CultureInfo.InvariantCulture)}',{id}";
        //                                        rtbInfo.Text = rtbInfo.Text + "\r\n"+ count2 +"/"+lostHours.Count+ "补:" + sqlStr;
        //                                        _skpwCommand.CommandText = sqlStr;
        //                                        _skpwCommand.ExecuteNonQuery();
        //                                    }
        //                                }

        //                            }
        //                            catch (Exception ex)
        //                            {
        //                                LogHelper.Error(typeof(FormMain), ex);
        //                                rtbError.Text = "补-->" + ex.Message + ex.StackTrace;
        //                            }
        //                            ThreadSleep(100);
        //                        }
        //                    }
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                LogHelper.Error(GetType(), DateTime.Now + "类：MainWindow，方法：ProcessBusiness，" + ex.Message);
        //                rtbError.Text = "补-->" + ex.Message + ex.StackTrace;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        rtbError.Text = "补-->" + ex.Message + ex.StackTrace;
        //    }
        //}
        private static void ThreadSleep(int i)
        {
            try
            {
                Thread.Sleep(i);
            }
            catch (Exception)
            {
                //
            }
        }

        //private void LoadData()
        //{
        //    try
        //    {
        //        string sqlString = "select top 1000 * from 绍兴排水流量表";
        //        ps_command.CommandText = sqlString;

        //        if (ps_connection.State == ConnectionState.Closed)
        //            ps_connection.Open();
        //        if (_skpwConnection.State == ConnectionState.Closed)
        //            _skpwConnection.Open();
        //        DataTable dt = new DataTable();
        //        _sda = new SqlDataAdapter(ps_command);
        //        _sda.Fill(dt);
        //        string ID, ps_Name, monitor_Time;
        //        decimal flow, total_Flow;
        //        string sqlStr = "";
        //        foreach (DataRow row in dt.Rows)
        //        {
        //            try
        //            {
        //                ID = row["ID"].ToString();
        //                if (row["用户名称"].ToString()!="")
        //                {
        //                    ps_Name = row["用户名称"].ToString();
        //                    monitor_Time = Convert.ToDateTime(row["日期"]).ToString("yyyy-MM-dd") + " " + row["时间"].ToString();
        //                    flow = Convert.ToDecimal(row["瞬时流量"]);
        //                    total_Flow = Convert.ToDecimal(row["累计流量"]);
        //                    sqlStr = string.Format("exec SP_UploadPS_Monitor_Data '{0}','{1}','{2}','{3}'", ps_Name, monitor_Time, flow.ToString(), total_Flow.ToString());
        //                    _skpwCommand.CommandText = sqlStr;
        //                    int returnValue = _skpwCommand.ExecuteNonQuery();
        //                }
        //                sqlStr = "delete from 绍兴排水流量表 where ID=" + ID;
        //                ps_command.CommandText = sqlStr;
        //                ps_command.ExecuteNonQuery();
        //            }
        //            catch (Exception ex)
        //            {
        //                WriteData("导入市排水公司的" + row["用户名称"].ToString() + "数据时，于" + DateTime.Now.ToString() + "发生错误，错误信息为：" + ex.Message);
        //                WriteData("");
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        WriteData("导入市排水公司数据时，于" + DateTime.Now.ToString() + "发生错误，错误信息为：" + ex.Message);
        //        WriteData("");
        //    }
        //}

        private void LoadXpsData()
        {
            try
            {
                string sqlString = "select Let_Port_ID,XPSName,LastMaxID from Envi_UploadXPSDataMapping";
                _skpwCommand.CommandText = sqlString;
                if (_skpwConnection.State == ConnectionState.Closed)
                    _skpwConnection.Open();
                DataTable allDt = new DataTable();
                _xpsSda = new SqlDataAdapter(_skpwCommand);
                _xpsSda.Fill(allDt);
                int psCount = allDt.Rows.Count;
                int count1 = 0;
                foreach (DataRow row in allDt.Rows)
                {
                    var begin = DateTime.Now;
                    count1++;
                    rtbInfo.Text = row["XPSName"].ToString();
                    try
                    {
                        var letPortId = row["Let_Port_ID"].ToString();
                        //                    sqlString =
                        //                       $"select top 1 * from {row["XPSName"]} WITH(NOLOCK) order by 时间标志 desc";
                        //                    _xpsCommand.CommandText = sqlString;
                        //                    DataTable dt2 = new DataTable();
                        //                    _sda = new SqlDataAdapter(_xpsCommand);
                        //                    _sda.Fill(dt2);
                        //                    foreach (DataRow rowT in dt2.Rows)
                        //                    {
                        //                        var id = rowT["时间标志"].ToString();
                        //                        string sql = string.Format(
                        //"UPDATE Envi_UploadXPSDataMapping SET LastMaxID={0} WHERE Let_Port_ID={1}", id, letPortId);
                        //                        _skpwCommand.CommandText = sql;
                        //                        _skpwCommand.ExecuteNonQuery();
                        //                    }

                        sqlString =
                            $"select top 100 * from {row["XPSName"]} WITH(NOLOCK) where 时间标志>{row["LastMaxID"]} order by 时间标志";
                        _xpsCommand.CommandText = sqlString;
                        if (_xpsConnection.State == ConnectionState.Closed)
                            _xpsConnection.Open();
                        if (_skpwConnection.State == ConnectionState.Closed)
                            _skpwConnection.Open();
                        DataTable dt = new DataTable();
                        _sda = new SqlDataAdapter(_xpsCommand);
                        _sda.Fill(dt);
                        int recordCount = dt.Rows.Count;
                        int count2 = 0;
                        if (recordCount < 1)
                        {
                            rtbError.Text = row["XPSName"] + "[" + count1 + "/" + psCount + "]" + "暂无数据";
                            LogHelper.Error(typeof(FormMain),
                                row["XPSName"] + "[" + count1 + "/" + psCount + "]" + "暂无数据");
                        }
                        else
                        {
                            rtbInfo.Text = row["XPSName"] + "开始传数据";

                            foreach (DataRow rowT in dt.Rows)
                            {
                                count2++;
                                try
                                {
                                    var id = rowT["时间标志"].ToString();
                                    string sql =
                                        string.Format(
                                            "UPDATE Envi_UploadXPSDataMapping SET LastMaxID={0} WHERE Let_Port_ID={1}",
                                            id, letPortId);
                                    _skpwCommand.CommandText = sql;
                                    _skpwCommand.ExecuteNonQuery();
                                    if (letPortId != "")
                                    {

                                        var monitorTime =
                                            Convert.ToDateTime(rowT["日期"]).ToString("yyyy-MM-dd") + " " + rowT["时间"];
                                        //var dateTime = DateTime.Parse(monitorTime);
                                        // if (dateTime > DateTime.Now.AddDays(-1) && dateTime < DateTime.Now.AddDays(1))// && dateTime.Minute < 16)//2013-01-21 严添加时间判断（如果检测时间延时不超过一天）
                                        //{
                                        var flow = Convert.ToDecimal(rowT["瞬时流量"]);
                                        var totalFlow = Convert.ToDecimal(rowT["累积流量"]);
                                        string sqlStr =
                                            $"exec SP_UploadSXXPS_Monitor_Data '{letPortId}','{monitorTime}','{flow.ToString(CultureInfo.InvariantCulture)}','{totalFlow.ToString(CultureInfo.InvariantCulture)}',{id}";
                                        rtbInfo.Text =
                                             "\n" + row["XPSName"] + "[" + count1 + "/" + psCount +
                                            "]" + "[" + count2 + "/" + recordCount + "]" + sqlStr + "\n" + rtbInfo.Text;
                                        _skpwCommand.CommandText = sqlStr;
                                        _skpwCommand.ExecuteNonQuery();
                                        //}
                                    }
                                    else
                                    {
                                        rtbError.Text = row["XPSName"] + "[" + count1 + "/" + psCount + "]" + "[" +
                                                        count2 + "/" + recordCount + "]" + "letPortId为空";
                                    }

                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Error(typeof(FormMain), ex);
                                    rtbError.Text = ex.Message + ex.StackTrace;
                                }

                                ThreadSleep(20);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(typeof(FormMain), ex);
                        rtbError.Text = ex.Message + ex.StackTrace;
                    }

                    rtbError.Text = "用时:" + (DateTime.Now - begin).TotalSeconds;
                }
                _skpwConnection.Close();
                _xpsConnection.Close();
            }
            catch (Exception ex)
            {
                try
                {
                    _skpwConnection.Close();
                    _xpsConnection.Close();
                }
                catch (Exception)
                {
                    //
                }
                LogHelper.Error(typeof(FormMain), ex);
                rtbError.Text = ex.Message + ex.StackTrace;
            }
        }



        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            var result = MessageBox.Show(@"确定关闭程序！", @"提示", MessageBoxButton.YesNo);
            if (result.Equals(MessageBoxResult.No))
            {
                e.Cancel = true;
            }
            else
            {
                Environment.Exit(0);
            }

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }
    }
}
